<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div style="display: flex;">
                    <div>
                        <el-date-picker :default-time="defaultTime" style="width: 340px;height:30px"
                            v-model="timeTypeTime" @change="timeTypeTime_btn" type="datetimerange"
                            start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss" />
                    </div>
                    <el-select clearable style="width:140px;margin-left: 10px;" v-model="find_data.balType"
                        placeholder="账户类型">
                        <el-option v-for="item in getCusBalanceTypes_list" :key="item.id" :label="item.text"
                            :value="item.id" />
                    </el-select>
                    <el-select clearable style="width:140px;margin-left: 10px;" v-model="find_data.payTypes"
                    placeholder="交易类型" multiple collapse-tags collapse-tags-tooltip>
                    <el-option label="订单付款" value="ORDER_PAY" />
                    <el-option label="充值" value="BALANCE_RECH" />
                </el-select>
                <el-select clearable style="width:140px;margin-left: 10px;" v-model="find_data.operStatus"
                    placeholder="收款状态" >
                    <el-option label="未收款" value="NOTGATH" />
                    <el-option label="已收款" value="ALGATH" />
                </el-select>
                    <el-input style="width: 150px;margin-left:10px" v-model="find_data.note" placeholder="订单详情"
                        clearable />
                    <el-input style="width: 150px;margin-left:10px" v-model="find_data.operMark" placeholder="操作编号"
                        clearable />
                  
                    <el-select style="width: 200px;margin-left: 10px;" filterable remote clearable
                        :filter-method="queryCusPageList" v-model="find_data.userId" placeholder="请选择客户名称">
                        <el-option v-for="(item, index) in cusOptions" :key="index" :label="item.cusCompanyName"
                            :value="item.userId"></el-option>
                    </el-select>
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                 <!-- 功能按钮 -->
                 <div style="margin-top:10px;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">收款</el-button>
                    <!-- <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button> -->
                </div>
                <div style="margin-top:10px;display: flex;">
                    <el-tag type="success">总金额:{{ totalMoney }}元</el-tag>
                    <el-divider direction="vertical"></el-divider>
                    <el-tag type="danger">已收款:{{ alGathMoney }}元</el-tag>
                    <el-divider direction="vertical"></el-divider>
                    <el-tag type="success">未收款:{{ notGathMoney }}元</el-tag>
                </div>
               
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'companyName'" #="{ row, column, $index }">
                                <span>{{row.realName +'-'+row.loginPhone }}</span>

                            </template>
                            <template v-if="item.field == 'balType'" #="{ row, column, $index }">
                                <span>{{ balType_api(row.balType) }}</span>

                            </template>
                            <template v-if="item.field == 'payType'" #="{ row, column, $index }">
                                <span>{{ payType_api(row.payType) }}</span>

                            </template>
                            
                            <template v-if="item.field == 'amoneyalBillMoney'" #="{ row, column, $index }">
                                <span>{{ Number(row.amoney) - Number(row.alBillMoney)}}</span>

                            </template>
                            <template v-if="item.field == 'receiveStatus'" #="{ row, column, $index }">
                                <span>{{ row.receiveStatus == 'UNPAID'?'未收款':row.receiveStatus == 'DEPOSIT_PAID'?'已收定金':row.receiveStatus == 'FULL_PAID'?'已收全款': ''}}</span>

                            </template>
                            <template v-if="item.field == 'tradeStatus'" #="{ row, column, $index }">
                                {{ row.tradeStatus == 'INCOME' ? '收入' : '支出' }}
                            </template>


                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
         <!-- 收款 -->
         <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="80%" :close-on-click-modal='false'>
            <el-form class="form_Css" :model="add_data" ref="offlineDispatchCar_ref" :inline="true">
                <el-form-item>
                    <el-input style="width: 120px" v-model="add_data.transName" placeholder="对方户名" clearable />
                </el-form-item>
                <el-form-item>
                    <el-input style="width: 120px" v-model="add_data.cusName" placeholder="客户名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-select v-model="add_data.timeType" :placeholder="'时间'" style="width: 100px">
                        <el-option :label="'添加时间'" value="0"></el-option>
                        <el-option :label="'交易时间'" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-date-picker style="width: 340px" v-model="timeTypeTime2" @change="timeTypeTime_btn2"
                        type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item>
                    <el-input style="width: 120px" v-model="add_data.tradeMoney" placeholder="交易金额" clearable />
                </el-form-item>
                <el-form-item>
                    <el-select clearable multiple collapse-tags collapse-tags-tooltip style="width: 150px"
                        v-model="add_data.moneyTypeIds" placeholder="请选择金额类型">
                        <el-option v-for="item in findMtypeCombo_list" :key="item.id" :label="item.typeName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input style="width: 150px" v-model="add_data.remark" placeholder="摘要" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button @click="add_data_find" type="primary">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="add_data_ok" type="primary">确认收款</el-button>
                </el-form-item>
            </el-form>
            <el-table @selection-change="add_selection_change_btn" :data="findBankTradeList_list" border fit
                :height="350" style="width: 100%;margin-bottom: 20px;">
                <el-table-column type="selection" width="35" />
                <el-table-column label="编号" width="55" fixed type="index" />
                <!-- <el-table-column width="120" property="companyNum" label="标示号" /> -->
                <el-table-column width="120" property="tradeTime" label="交易时间" />
                <el-table-column width="120" property="settleUserName" label="下帐人" />
                <el-table-column width="120" property="myBankName" label="银行名称" />
                <el-table-column width="120" property="myBankNum" label="我的银行账号" />
                <el-table-column width="120" property="isCheck" label="报销状态">
                    <template #="{ row, column, $index }">
                        <span>{{ row.isCheck == 'REFUSED' ? '已拒绝' : row.isCheck == 'NO_CHECK' ? '未审核' :
                            row.isCheck
                                ==
                                'CHECKED' ? '已审核' : row.isCheck == 'CANCELLATION' ? '已报销' : row.isCheck == 'SETTLED' ?
                                    '已结算' : '' }} </span>

                    </template>
                </el-table-column>
                <el-table-column width="120" property="moneyTypeName" label="金额类型" />
                <el-table-column width="120" property="cusName" label="客户名称" />
                <el-table-column width="120" property="tradeInMoney" label="借" />
                <el-table-column width="120" property="transName" label="对方户名" />
                <el-table-column width="120" property="transNum" label="对方账号" />
                <el-table-column width="120" property="addTime" label="添加时间" />
                <el-table-column width="120" property="tradeOutMoney" label="贷" />
                <el-table-column width="120" property="balance" label="余额" />
                <el-table-column width="120" property="remark" label="摘要" />
                <el-table-column width="120" property="opermark" label="操作备注" />
            </el-table>
            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn2" @size-change="size_change_btn2"
                    v-model:current-page="add_data.page.pageNum" v-model:page-size="add_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total2" />
            </div>
            <el-form-item label="收款备注：" style="width: 220px;margin-top:20px">
                <el-input v-model="serviceGath_data.note" placeholder="收款备注" clearable />
            </el-form-item>

        </el-dialog>
  
    </div>
</template>

<script setup>
import * as XLSX from 'xlsx';
import Sortable from 'sortablejs';
import AMapLoader from "@amap/amap-jsapi-loader"
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, getWalletListForPlatBill, getCusBalanceTypes, findComboCusList, gathPlatBill,
    findBankTradeList,findMtypeCombo

} from '@/api/financial_center.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData, line2treeData, securityJsCode, key, } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    findMtypeCombo({}).then(res => {
        findMtypeCombo_list.value = res.data
    })

    getPrivateSetList({
        find: '收平台款',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })


    timeTypeTime.value = [new_day(), to_day()]
    find_data.stime = new_day()
    find_data.etime = to_day()
    getCusBalanceTypes({}).then(res => {
        getCusBalanceTypes_list.value = res.data
    })
    findComboCusList({
        find: '',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.code == 1) {
            cusOptions.value = res.data;
            cusOptions2.value = res.data;

            // 追加已选中的数据
            // if (cusObjArr.value.length > 0) cusOptions.value = cusObjArr.value.concat(cusOptions.value);
        }
    })

    await list_api()




})
const getCusBalanceTypes_list = ref([])
const balType_api = (e) => {
    let data = ''
    for (let i = 0; i < getCusBalanceTypes_list.value.length; i++) {
        if (e == getCusBalanceTypes_list.value[i].id) {
            data = getCusBalanceTypes_list.value[i].text
        }
    }
    return data
}
const payType_api = (e) => {
    let data = ''
    if (e == 'ORDER_PAY') {
        data = '订单付款'
    } else if (e == 'BALANCE_RECH') {
        data = '充值'
    }
    return data
}

const cusOptions = ref([])
const cusOptions2 = ref([])
const queryCusPageList = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = cusOptions2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            cusOptions.value = results
        } else {
            cusOptions.value = []
        }
    } else {
        cusOptions.value = cusOptions2.value
    }
}

const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const timeTypeTime = ref('')
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}
const to_day = () => {
    // 获取当前日期
    let currentDate = new Date();

    // 计算上个月的年份和月份
    let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
    let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

    // 获取上个月的最后一天
    let lastDayOfLastMonth = new Date(year, month + 1, 0);

    // 格式化为 yyyy-mm-dd
    let formattedDate = `${lastDayOfLastMonth.getFullYear()}-${(lastDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-${lastDayOfLastMonth.getDate()}`;

    let formattedDate2 = `${formattedDate} 23:59:59`;
    return formattedDate2
}
const handleFilter_change = (e) => {
    for (let i = 0; i < serviceCenterfindComboCusList_list2.value.length; i++) {
        if (serviceCenterfindComboCusList_list2.value[i].userId == e) {
            find_data.id = serviceCenterfindComboCusList_list2.value[i].id
        }
    }
}
const handleFilter = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = serviceCenterfindComboCusList_list2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            serviceCenterfindComboCusList_list.value = results
        } else {
            serviceCenterfindComboCusList_list.value = []
        }
    } else {
        serviceCenterfindComboCusList_list.value = serviceCenterfindComboCusList_list2.value
    }
}
const new_day = () => {
    // 获取当前日期
    let currentDate = new Date();

    // 计算上个月的年份和月份
    let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
    let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

    // 构建上个月的日期
    let firstDayOfLastMonth = new Date(year, month, 1);

    // 格式化为 yyyy-mm-dd
    let formattedDate = `${firstDayOfLastMonth.getFullYear()}-${(firstDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-01`;

    let formattedDate2 = `${formattedDate} 00:00:00`;
    return formattedDate2
}
//#region 表格数据处理
const table_data_list = reactive([
    { label: '客户信息', field: 'companyName', width: 190, off: true },
    { label: '账户类型', field: 'balType', width: 120, off: true },
    { label: '交易类型', field: 'payType', width: 165, off: true },
    { label: '账单详情', field: 'note', width: 440, off: true },
    { label: '收款状态', field: 'receiveStatus', width: 440, off: true },
    { label: '账单金额', field: 'amoney', width: 120, off: true },
    { label: '已收金额', field: 'alBillMoney', width: 120, off: true },
    { label: '应收金额', field: 'amoneyalBillMoney', width: 120, off: true },
    { label: '操作编号', field: 'operMark', width: 400, off: true },
    { label: '操作备注', field: 'operNote', width: 400, off: true },
    // { label: '收入状态', field: 'tradeStatus', width: 100, off: true },
 
    // { label: '现金余额', field: 'cashBalance', width: 120, off: true },
   
    { label: '添加时间', field: 'addTime', width: 190, off: true },

])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))

}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '收平台款',
        tbNum: "getWalletListForPlatBill",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 收款 
const add_table_list = ref([])
const add_selection_change_btn = (e) => {
    add_table_list.value = e
}
const add_off = ref(false)
const title = ref('添加收业务款')
const add_data = reactive({
    tradeStatus: '0',
    transName: '',
    cusName: "",
    timeType: "0",
    stime: "",
    etime: "",
    tradeMoney: '',
    moneyTypeIds: [2],
    remark: '',
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    isCheck: 'NO_CHECK',
})
const add_btn = () => {
    if (table_list.value.length < 1) {
        return ElMessage({
            message: '请选择至少一条数据！',
            type: 'warning',
        })
    }
    title.value = '收款'

    serviceGath_data.btlIds  = []
    serviceGath_data.ids  = []
    serviceGath_data.note  = ''
    findBankTradeList_api()
    add_off.value = true


}
const add_data_find = () => {
    findBankTradeList_api()
}
const findBankTradeList_list = ref([])

const total2 = ref(0)
const current_change_btn2 = () => {
    findBankTradeList_api()
}
// 分页器一夜显示多少数据页面
const size_change_btn2 = () => {
    add_data.page.pageNum = 1
    findBankTradeList_api()
}
const findBankTradeList_api = () => {
    findBankTradeList(add_data).then(res => {
        findBankTradeList_list.value = res.data.list.list

        total2.value = res.data.list.total
    })
}
const timeTypeTime2 = ref('')
const timeTypeTime_btn2 = (e) => {
    if (e) {
        timeTypeTime2.value = e
        add_data.stime = timeTypeTime2.value[0]
        add_data.etime = timeTypeTime2.value[1]
    } else {
        timeTypeTime2.value = ''
        add_data.stime = ''
        add_data.etime = ''
    }
}
const findMtypeCombo_list = ref([])
const serviceGath_data = reactive({
    btlIds: [],
    ids: [],
    note : '',
})
const add_data_ok = () => {
    if (add_table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    let ids = []
    for (let i = 0; i < table_list.value.length; i++) {
        ids.push(table_list.value[i].id)
    }
    let btlIds = []
    for (let i = 0; i < add_table_list.value.length; i++) {
        btlIds.push(add_table_list.value[i].id)
    }
    serviceGath_data.ids = ids
    serviceGath_data.btlIds = btlIds
    gathPlatBill(serviceGath_data).then(res => {
        if (res.code == 1) {
            list_api()
            add_off.value = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
}

//#endregion

//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    balType: '',
    stime: '',
    etime: '',
    note: '',
    payTypes: [],
    userId: '',
    operMark: '',
    operStatus: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    getWalletListForPlatBill(find_data).then(res => {
        list_data.value = res.data.list.list
        total.value = res.data.list.total
        totalMoney.value = res.data.statics.totalMoney
        alGathMoney.value = res.data.statics.alGathMoney
        notGathMoney.value = res.data.statics.notGathMoney
    })
}
//#endregion


//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}

const totalMoney = ref(0)
const alGathMoney = ref(0)
const notGathMoney = ref(0)




//#endregion

//#region 搜索
const search_btn = () => {

    list_api()
}
//#endregion
</script>

<style scoped lang='scss'>
.div_map {
    position: relative;
    left: 0;
    top: 0;
}

.map_input {
    width: 100%;
    position: absolute;
    z-index: 1;
    display: flex;
    justify-content: center;

}

.map_input2 {
    width: 100%;
    position: absolute;
    z-index: 1;
    display: flex;
    justify-content: center;
    top: 34px;

}

.div_bg:hover {


    background-color: darkgray;
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
